package com.ruoyi.seckill.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.seckill.service.SeckillTestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.atomic.AtomicInteger;

@RestController
@RequestMapping("/seckill")
public class SeckillTestController {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Value("${server.port}")
    private String port;

    private AtomicInteger atomicInteger = new AtomicInteger(0);

    @Autowired
    private SeckillTestService seckillTestService;

    @GetMapping(value = "/grab", produces = "application/json;charset=UTF-8")
    @SentinelResource(
            value = "seckillGrab",
            blockHandler = "handleSeckillBlock",
            fallback = "fallSeckillBlock"
    )
    public AjaxResult grab(@RequestParam("userId") String userId) {

        String seckill = seckillTestService.createSeckill(userId);
        return AjaxResult.success("调用 order 成功，结果：" + seckill);
    }

    public AjaxResult handleSeckillBlock(String userId, BlockException ex) {
        System.out.println("当前访问人数过多，请稍后再试！");
        return AjaxResult.error("当前访问人数过多，请稍后再试！");
    }

    public AjaxResult fallSeckillBlock(String userId, Throwable  ex) {
        System.out.println("报错了");
        return AjaxResult.error("报错了！");
    }

}

